package com.shujia.spark

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

object Demo11Join {
  def main(args: Array[String]): Unit = {

    val conf: SparkConf = new SparkConf()
      .setMaster("local")
      .setAppName("Demo10Union")


    val sc = new SparkContext(conf)

    val namesRDD: RDD[(String, String)] = sc.makeRDD(List(("001", "张三"), ("002", "李四")))
    val agesRDD: RDD[(String, Int)] = sc.makeRDD(List(("002", 24), ("003", 25)))


    /**
      * inner join； 通过rdd的key进行关联
      *
      */
    val innerJoinRDD: RDD[(String, (String, Int))] = namesRDD.join(agesRDD)

    //关联之后处理数据
    val rdd1: RDD[(String, String, Int)] = innerJoinRDD.map {
      case (id: String, (name: String, age: Int)) =>
        (id, name, age)
    }
    //rdd1.foreach(println)


    /**
      * left join : 以左表为主，如果右表为没有，补null
      *
      */

    val leftJoinRDD: RDD[(String, (String, Option[Int]))] = namesRDD.leftOuterJoin(agesRDD)


    //整理数据

    val rdd2: RDD[(String, String, Int)] = leftJoinRDD.map {
      //匹配关联成功的数据
      case (id: String, (name: String, Some(age))) =>
        (id, name, age)

      //匹配没有关联成功的数据
      case (id: String, (name: String, None)) =>
        //没有关联可以给一个默认值
        (id, name, 0)
    }

    // rdd2.foreach(println)

    /**
      * full join: 两边都可能关联不是， 补null
      *
      */

    val fullJOinRDD: RDD[(String, (Option[String], Option[Int]))] = namesRDD.fullOuterJoin(agesRDD)

    //整理数据
    val rdd3: RDD[(String, String, Int)] = fullJOinRDD.map {
      case (id: String, (Some(name), Some(age))) =>
        (id, name, age)

      case (id: String, (None, Some(age))) =>
        (id, "默认值", age)

      case (id: String, (Some(name), None)) =>
        (id, name, 0)
    }

    rdd3.foreach(println)

  }

}
